package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
	"strings"
	"uds-saas-go-parser/common"
	"uds-saas-go-parser/manage"
)

func readFileByScanner(filename string) error {
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	lineNumber := 1

	allParsedRawData := []any{}

	lstRawData := list.New()

	currentTypeName := ""

	rawDataCached := []string{}
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Printf("Line %d: %s\n", lineNumber, line)
		lineNumber++

		if currentTypeName == common.CYCLE {
			if strings.HasPrefix(line, common.CYCLEOFF) {
				currentTypeName = ""
				lstRawData.PushBack(common.ParsedRawData{Type: common.CYCLE, RawData: rawDataCached})
				continue
			}
			rawDataCached = append(rawDataCached, line)
		} else if currentTypeName == common.PAINT {
			if strings.HasPrefix(line, common.RAPID) || strings.HasPrefix(line, common.FEDRAT) {
				rawDataCached = append(rawDataCached, line)
			}
			lstRawData.PushBack(common.ParsedRawData{Type: common.PAINT, RawData: rawDataCached})
			currentTypeName = ""
		} else {
			if strings.HasPrefix(line, common.GOTO) {
				lstRawData.PushBack(common.ParsedRawData{Type: common.GOTO, RawData: []string{line}})
			} else if strings.HasPrefix(line, common.CIRCLE) {
				lstRawData.PushBack(common.ParsedRawData{Type: common.CIRCLE, RawData: []string{line}})
			} else if strings.HasPrefix(line, common.CYCLE) && !strings.HasPrefix(line, common.CYCLEOFF) {
				rawDataCached = []string{}
				rawDataCached = append(rawDataCached, line)
				currentTypeName = common.CYCLE
			} else if strings.HasSuffix(line, common.END) {
				manage.ParseRawData(lstRawData)
				manage.JoinTogether(lstRawData)
				allParsedRawData = append(allParsedRawData, lstRawData)
				lstRawData = list.New()
			} else if strings.HasPrefix(line, common.PAINT) { // 必须在common.END后面
				rawDataCached = []string{}
				rawDataCached = append(rawDataCached, line)
				currentTypeName = common.PAINT
			}

		}

	}

	if err := scanner.Err(); err != nil {
		return err
	}

	return nil
}

func main() {
	readFileByScanner("./APT/Spotting.apt")
}
